<?php
include('Misc/DatabaseConnection.php');
include('Misc/Settings.php');

	
class TurnModel
{
	private $db = NULL;
	public function __construct()
	{
		$database = new DatabaseConnection(Settings::DbSettings());
		$database->Connect();
		$this->db = $database;
	}
		
	public function UpdateReadyStatus($gameId, $userId, $ready)
	{
		if($stmt = $this->db->getPrepareStatement("UPDATE PlayerTurns
		     									 SET Ready=?
		     									 WHERE UserId=? AND GameId=?"))
    		{
    			$stmt->bind_param("iii", $ready, $userId, $gameId);
    			if($stmt->execute())
    			{
    				$stmt->close();
    				return true;
    			}
    		}
    		return false;
	}
	public function checkIfAllPlayersIsReady($gameId)
	{
		$objArray = null;
		
		if($stmt = $this->db->getPrepareStatement("SELECT UserID, Ready 
											 FROM PlayerTurns 
											 WHERE GameId=?"))
		{
			$stmt->bind_param("i", $gameId);
			$stmt->execute();
			$stmt->bind_result($id,$readyStatus);
			while($stmt->fetch())
			{
				$obj = array("userId" => $id, "readyStatus" => $readyStatus); 
				$objArray[] = $obj; 
			}
			$stmt->close();
			
			foreach($objArray as $user)
			{
				if($user["readyStatus"] == false)
				{
					return false;
				}
			}
			return true;
		}
	}
	public function setReadyStatusToFalse($gameId)
	{
		if($stmt = $this->db->getPrepareStatement("UPDATE PlayerTurns 
											 SET Ready = 0 
											 WHERE GameId=?"))
		{
			$stmt->bind_param("i", $gameId);
			$stmt->execute();
			$stmt->close();
		}
	}
	public function getReadyStatus($gameId, $userId)
	{
		if($stmt = $this->db->getPrepareStatement("SELECT Ready
											 FROM PlayerTurns 
											 WHERE GameID=? AND UserId=?"))
		{
		 	$stmt->bind_param("ii", $gameId, $userId);
			$stmt->execute();
			$stmt->bind_result($readyStatus);
			while($stmt->fetch())
			{
				$status = $readyStatus;
			}
			$stmt->close();
			return $status;
		}
	}
}
